from django.shortcuts import render,HttpResponse
from django.conf import settings
import random
from utils.sms import send_sms_single
from .forms import RegisterModelForm
from .qcloud_cos import client
from django_redis import get_redis_connection
import re
def index(request):
    if request.method == 'GET':
        return render(request,'index.html')
    else:
        stream=request.FILES.get('file')
        if stream :
            file_name=stream.name
            response = client.put_object(
                Bucket=settings.BUCKET,
                Body=stream,
                Key=file_name
            )
            print(response['ETag'])
    
            return HttpResponse('上传成功')
        else:
            return HttpResponse('上传文件为空')

def send_sms(request):

    tpl = request.GET.get('tpl')
    template_id = settings.TENCENT_SMS_TEMPLATE.get(tpl)
    phone=request.GET.get('phone')
    ret = re.match(r"^1[35789]\d{9}$", phone)
    if not ret:
        return HttpResponse('手机号码错误')
    if not template_id:
            return HttpResponse('模板不存在')
    else:
        code = random.randrange(1000, 9999)
        conn = get_redis_connection("default")
        conn.set(phone,code, ex=60)
        res = send_sms_single(phone,template_id,[code,])
        if res['result'] == 0:
            return HttpResponse('成功')
        else:
            return HttpResponse(res['errmsg'])




def register(request):
    if request.method == 'GET':
        form=RegisterModelForm()
        return render(request,'register.html',{'form':form})
    elif request.method=='POST':
        code=request.POST.get('code')
        phone=request.POST.get('mobile_phone')
        conn = get_redis_connection("default")
        value=conn.get(phone)
        if value:
            if int(value) == int(code):
                form_set=RegisterModelForm(data=request.POST)
                if form_set.is_valid():
                    form_set.save()
                    return HttpResponse('注册成功')
                else:
                    return HttpResponse(form_set.errors)

        return HttpResponse('验证码失效或错误')
